package com.oneguy.control.queue;

public class MessageQueue {
	private class MessageEntry {
		Message element;
		MessageEntry next;
		MessageEntry previous;
	}

	private MessageEntry head;
	private MessageEntry tail;
	private int size = 0;

	public MessageQueue() {
		head = new MessageEntry();
		tail = new MessageEntry();
		head.next = tail;
		tail.previous = head;
		size = 0;
	}

	public Message peek() {
		if (size == 0) {
			return null;
		} else {
			return head.next.element;
		}
	}

	public Message poll() {
		if (size == 0) {
			return null;
		} else {
			size--;
			MessageEntry headNext = head.next;
			head.next = headNext.next;
			headNext.next.previous = head;
			headNext.previous = null;
			headNext.next = null;
			return headNext.element;
		}
	}

	public void offer(Message msg) {
		MessageEntry entry = new MessageEntry();
		MessageEntry previous = tail.previous;
		MessageEntry next = tail;
		entry.element = msg;
		while (previous != head && previous.element.when > entry.element.when) {
			next = previous;
			previous = previous.previous;
		}
		entry.previous = previous;
		entry.next = next;
		previous.next = entry;
		next.previous = entry;
		size++;
	}

	public int size() {
		return size;
	}

}
